﻿using album.Feature;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace album.Controllers
{

    [ApiController]
    [Route("[controller]/[action]")]
    public class AlbumController : ControllerBase
    {

        private string _albumPath = Directory.GetCurrentDirectory() + "\\App_Data\\";

        //添加目录
        [HttpGet]
        public int AddDirector(string path)
        {
            if (Directory.Exists(path))
            {
                return 500;
            }
            try
            {
                Directory.CreateDirectory(path);
                return 200;
            }
            catch
            {
                return -1;
            }
        }

        //获取目录
        [HttpGet]
        public ActionResult<List<PhotoDirectory>> GetDirector(string path)
        {
            var absolutePath = "";
            if (path == "0" || "undefined" == path || null == path)
            {
                path = "";
                absolutePath = _albumPath;
            }
            else
            {
                absolutePath = _albumPath + path;
            }
            DirectoryInfo root = new DirectoryInfo(absolutePath);
            DirectoryInfo[] dics = root.GetDirectories();
            List<PhotoDirectory> directorList = new List<PhotoDirectory>();
            foreach (DirectoryInfo f in dics)
            {
                PhotoDirectory photoDirectory = new PhotoDirectory();
                photoDirectory.Name = f.Name;
                photoDirectory.Path = path + "\\" + f.Name;
                photoDirectory.parPath = absolutePath;
                directorList.Add(photoDirectory);
            }
            return directorList;
        }

        [HttpGet]
        public ActionResult<List<ImgInfo>> GetFile(string path)
        {
            var absolutePath = "";
            if (path == "0" || "undefined" == path || null == path)
            {
                path = "";
                absolutePath = _albumPath;
            }
            else
            {
                absolutePath = _albumPath + path;
            }

            DirectoryInfo root = new DirectoryInfo(absolutePath);
            List<ImgInfo> imgData = new List<ImgInfo>();

            foreach (FileInfo f in root.GetFiles())
            {
                try
                {
                    ImgInfo imgInfo = new ImgInfo();
                    imgInfo.Title = f.Name.Replace(f.Name.Substring(f.Name.IndexOf('.')), "");//去除后缀
                    imgInfo.fullTitle = f.Name;
                    imgInfo.ImgSrc = f.FullName;
                    imgInfo.parPath = path;
                    imgData.Add(imgInfo);
                }
                catch (Exception ex)
                {
                    continue;
                }
            }
            return imgData;
        }

        [HttpGet("{id}")]
        public ActionResult<List<string>> Get(int id)
        {
            string path = _albumPath;
            DirectoryInfo root = new DirectoryInfo(path);
            List<string> directoryList = new List<string>();
            foreach (DirectoryInfo NextFolder in root.GetDirectories())
            {
                string dicName = NextFolder.Name;
                directoryList.Add(dicName);
            }
            return directoryList;
        }

        [HttpGet]
        public int EditTitle(string title, string path, string newName)
        {
            if (!System.IO.File.Exists(path))
            {
                return 500;
            }
            FileInfo fi = new System.IO.FileInfo(path);
            string newPath = path.Replace(title, newName);
            if (System.IO.File.Exists(newPath))
            {
                return -1;
            }

            try
            {
                fi.MoveTo(newPath);
                return 200;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <param name="directoryPath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Uploadfile([FromForm] IFormFile file)
        {
            string FileTypes = ".gif,.jpg,.jpeg,.png,.bmp,.GIF,.JPG,.JPEG,.PNG,.BMP";
            if (file.Length <= 10485760)//检查文件大小
            {
                var suffix = Path.GetExtension(file.FileName);//提取上传的文件文件后缀
               var fileName = "abc." + suffix;
                if (FileTypes.IndexOf(suffix) >= 0)//检查文件格式
                {
                    using (FileStream fs = System.IO.File.Create(fileName))//注意路径里面最好不要有中文
                    {
                        file.CopyTo(fs);//将上传的文件文件流，复制到fs中
                        fs.Flush();//清空文件流
                        fs.Close();
                    }
                    return StatusCode(200, new { newFileName = fileName });//将新文件文件名回传给前端
                }
                else
                    return StatusCode(415, new { msg = "不支持此文件类型" });//类型不正确
            }
            else
            {
                return StatusCode(413, new { msg = $"文件大小不得超过{10485760 / (1024f * 1024f)}M" });//请求体过大，文件大小超标
            }
        }


        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <param name="directoryPath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Upload([FromForm] IFormFile file, string directoryPath, string fileName)
        {
            string FileTypes = ".gif,.jpg,.jpeg,.png,.bmp,.GIF,.JPG,.JPEG,.PNG,.BMP";
            if ("" == fileName || "undefined" == fileName || null == fileName)
            {
                fileName = DateTime.Now.ToString("yyyyMMddHHmmss");
            }
            if (file.Length <= 10485760)//检查文件大小
            {
                var suffix = Path.GetExtension(file.FileName);//提取上传的文件文件后缀
                fileName = _albumPath + directoryPath + "\\" + fileName + suffix;
                if (FileTypes.IndexOf(suffix) >= 0)//检查文件格式
                {
                    using (FileStream fs = System.IO.File.Create(fileName))//注意路径里面最好不要有中文
                    {
                        file.CopyTo(fs);//将上传的文件文件流，复制到fs中
                        fs.Flush();//清空文件流
                        fs.Close();
                    }
                    return StatusCode(200, new { newFileName = fileName });//将新文件文件名回传给前端
                }
                else
                    return StatusCode(415, new { msg = "不支持此文件类型" });//类型不正确
            }
            else
            {
                return StatusCode(413, new { msg = $"文件大小不得超过{10485760 / (1024f * 1024f)}M" });//请求体过大，文件大小超标
            }
        }

        /// <summary>
        /// 获取图片
        /// </summary>
        /// <param name="imgPath"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAllImage(string imgPath)
        {
            FileInfo fi = new FileInfo(imgPath);
            if (!fi.Exists)
            {
                return null;
            }

            FileStream fs = fi.OpenRead();
            byte[] buffer = new byte[fi.Length];
            //读取图片字节流
            //从流中读取一个字节块，并在给定的缓冲区中写入数据。
            fs.Read(buffer, 0, Convert.ToInt32(fi.Length));
            var resource = File(buffer, "image/jpeg");

            var image = resource;
            if (image == null)
            {

            }
            //fs.Flush();
            fs.Flush();
            //fs.Dispose();
            fs.Close();
            return image;
        }

    }

}
